﻿using System;
using System.Collections.Generic;
using System.IO;

namespace ZenWplExporter
{
	internal class ZenPlayListBuilder
	{
		private readonly Id3TagReader _mp3TagReader = new Id3TagReader();
		private readonly WmaTagReader _wmaTagReader = new WmaTagReader();

		/// <summary>
		/// Builds the list from the specified source files.
		/// </summary>
		/// <param name="sourceFiles">The source files.</param>
		/// <param name="zenMusicDir">The root music dir on ZEN device (e.g. F:\Music).</param>
		/// <param name="organizeByAuthorAlbum">if set to <c>true</c> then use organization by author and album.</param>
		/// <returns></returns>
		public ZenPlayList Build(IEnumerable<string> sourceFiles, string zenMusicDir, bool organizeByAuthorAlbum)
		{
			var list = new ZenPlayList();

			foreach (var file in sourceFiles)
			{
				list.Items.Add(GetZenFilePath(file, zenMusicDir, organizeByAuthorAlbum));
			}

			return list;
		}

		private string GetZenFilePath(string sourcePath, string zenMusicDir, bool organizeByAuthorAlbum)
		{
			string fileName = Path.GetFileName(sourcePath);
			string zenFilePath;

			if (organizeByAuthorAlbum)
			{
				var ext = Path.GetExtension(sourcePath).ToLower();

				MusicFileInfo info;

				switch (ext)
				{
					case ".mp3":
						info = _mp3TagReader.ReadMusicInfo(sourcePath);
						break;
					case ".wma":
						info = _wmaTagReader.ReadMusicInfo(sourcePath);
						break;
					default:
						throw new NotSupportedException(String.Format("Canot process {0}. {1} file format is not supported.", sourcePath, ext));

				}

				zenFilePath = ZenFileLocator.LocateFile(zenMusicDir, info.Artist, info.Album, fileName);
			}
			else
			{
				zenFilePath = ZenFileLocator.LocateFile(zenMusicDir, fileName);
			}

			return zenFilePath.Substring(2); // Do not include drive letter.
		}
	}
}